package org.lyd.spring.aop.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/**
 * @Author:lyd
 **/
//指定切面顺序，数字越小优先级越高
@Order(-1)
@Component
@Aspect
public class LogAspect {
    @Pointcut("execution(int org.lyd.spring.aop.calculator.Calculator.*(..))")
    public void pointCut() {
    }

   @Before("pointCut()")
//    @Before("execution(int org.lyd.spring.aop.calculator.Calculator.add(int ,int ))")
    public void logStart(JoinPoint joinPoint) {
        //获取参数
        Object[] args = joinPoint.getArgs();
        //获取方法名
        String name = joinPoint.getSignature().getName();
        System.out.println("【log】-->" + name + "执行,参数为：" + Arrays.toString(args));
    }

//    @AfterReturning(value = "execution(int org.lyd.spring.aop.calculator.Calculator.add(int ,int ))",
//            returning = "result")
    @AfterReturning(value = "pointCut()",returning = "result")
    public void logReturn(JoinPoint joinPoint, Object result) {
        String name = joinPoint.getSignature().getName();
        System.out.println("【log】-->" + name + "返回-->方法执行,结果为：" + result);
    }

//    @After("execution(int org.lyd.spring.aop.calculator.Calculator.add(int ,int ))")
    @After("pointCut()")
    public void logEnd(JoinPoint joinPoint) {
        String name = joinPoint.getSignature().getName();
        System.out.println("【log】-->" + name + "执行结束");
    }

    //    @AfterThrowing(value = "execution(int org.lyd.spring.aop.calculator.Calculator.add(int ,int ))",
//    throwing = "exception")
    @AfterThrowing(value = "pointCut()",throwing = "exception")
    public void logException(JoinPoint joinPoint, Exception exception) {
        String name = joinPoint.getSignature().getName();
        System.out.println("【log】-->" + name + "异常-->方法执行,异常为：" + exception.getMessage());
    }
}
